package swing.admin.views.main;

import swing.admin.common.BaseMainCard;
import swing.admin.dao.UserDao;
import swing.admin.model.User;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.List;

public class UserMainCard extends BaseMainCard {

    private UserDao userDao = new UserDao();
    private final String[] header = {"ID", "用户名", "密码"};
    private java.util.List<User> data;


    public UserMainCard(String menuName) {
        super(menuName);
        this.data = userDao.listAll();
        this.model = createTableModel();
        this.table = createTable();

        this.setLayout(new BorderLayout());
        this.add(createOperatePanel(), BorderLayout.NORTH);
        this.add(createTablePanel(), BorderLayout.CENTER);

        refreshTableModel();
    }

    private JPanel createOperatePanel() {
        JPanel panel = new JPanel();

        JTextField text = new JTextField();
        text.setPreferredSize(new Dimension(200, 27));
        panel.add(text);

        JButton query = new JButton("查询");
        query.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (text.getText().equals("")) {
                    refreshData(userDao.listAll());
                } else {

                    refreshData(userDao.list(new User(null, text.getText(), null)));
                }
            }
        });
        panel.add(query);


        JButton reset = new JButton("重置");
        reset.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                text.setText("");
            }
        });
        panel.add(reset);

        JButton add = new JButton("新增");
        add.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                UserAddDialog dialog = new UserAddDialog();
                dialog.setVisible(true);
            }
        });
        panel.add(add);

        return panel;
    }

    private void refreshData(List<User> data) {
        this.data = data;
        refreshTableModel();
    }

    private void refreshTableModel() {
        model.setRowCount(0);
        data.forEach(user -> {
            model.addRow(new Object[]{user.getId(), user.getUsername(), user.getPassword()});
        });
    }

    private JScrollPane createTablePanel() {
        this.table = this.createTable();
        JScrollPane panel = new JScrollPane(table);
        return panel;
    }

    public JTable createTable() {
        JTable table = new JTable(model);
        table.setRowHeight(30);

        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    Integer id = (Integer) model.getValueAt(table.getSelectedRow(), 0);
                    System.out.println(id);
                    new UserDetailsDialog(userDao.getById(id)).setVisible(true);
                }
            }
        });
        return table;
    }

    private DefaultTableModel createTableModel() {
        DefaultTableModel tableModel = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        Arrays.stream(header).forEach(tableModel::addColumn);
        return tableModel;
    }

    class UserDetailsDialog extends JDialog {

        private JTextField idField;
        private JTextField usernameField;
        private JPasswordField passwordField;

        private User user;

        public UserDetailsDialog(User user) {
            super((Frame) null, "用户详情", true);
            this.user = user;
            setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            setSize(300, 200);
            setLocationRelativeTo(null);
            setResizable(false);

            initComponents();

        }

        private void initComponents() {
            // 创建并设置布局
            JPanel contentPane = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5, 5, 5, 5);

            // ID
            gbc.gridx = 0;
            gbc.gridy = 0;
            JLabel idLabel = new JLabel("ID:");
            contentPane.add(idLabel, gbc);

            gbc.gridx = 1;
            gbc.gridy = 0;
            idField = new JTextField(20);
            idField.setText(String.valueOf(user.getId()));
            idField.setEditable(false);
            idField.setPreferredSize(new Dimension(200, 27));
            contentPane.add(idField, gbc);

            // Username
            gbc.gridx = 0;
            gbc.gridy = 1;
            JLabel usernameLabel = new JLabel("用户名:");
            contentPane.add(usernameLabel, gbc);

            gbc.gridx = 1;
            gbc.gridy = 1;
            usernameField = new JTextField(20);
            usernameField.setText(user.getUsername());
            usernameField.setPreferredSize(new Dimension(200, 27));
            contentPane.add(usernameField, gbc);

            // Password
            gbc.gridx = 0;
            gbc.gridy = 2;
            JLabel passwordLabel = new JLabel("密码:");
            contentPane.add(passwordLabel, gbc);

            gbc.gridx = 1;
            gbc.gridy = 2;
            passwordField = new JPasswordField(20);
            passwordField.setText(user.getPassword());
            passwordField.setPreferredSize(new Dimension(200, 27));
            contentPane.add(passwordField, gbc);


            JPanel panel = new JPanel();
            JButton save = new JButton("保存");
            save.addActionListener(new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    userDao.updateById(new User(Integer.valueOf(idField.getText()), usernameField.getText(), passwordField.getText()));
                    refreshData(userDao.listAll());
                    dispose();
                }
            });
            panel.add(save);

            JButton delete = new JButton("删除");
            delete.addActionListener(new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    userDao.deleteById(user.getId());
                    refreshData(userDao.listAll());
                    dispose();
                }
            });
            panel.add(delete);

            setLayout(new BorderLayout());
            add(contentPane, BorderLayout.CENTER);
            add(panel, BorderLayout.SOUTH);
        }
    }


    class UserAddDialog extends JDialog {

        private JTextField usernameField;
        private JPasswordField passwordField;

        private User user;


        public UserAddDialog() {
            super((Frame) null, "新增用户", true);
            setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            setSize(300, 200);
            setLocationRelativeTo(null);
            setResizable(false);

            initComponents();

        }

        private void initComponents() {
            // 创建并设置布局
            JPanel contentPane = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5, 5, 5, 5);


            // Username
            gbc.gridx = 0;
            gbc.gridy = 1;
            JLabel usernameLabel = new JLabel("用户名:");
            contentPane.add(usernameLabel, gbc);

            gbc.gridx = 1;
            gbc.gridy = 1;
            usernameField = new JTextField(20);
            usernameField.setPreferredSize(new Dimension(200, 27));
            contentPane.add(usernameField, gbc);

            // Password
            gbc.gridx = 0;
            gbc.gridy = 2;
            JLabel passwordLabel = new JLabel("密码:");
            contentPane.add(passwordLabel, gbc);

            gbc.gridx = 1;
            gbc.gridy = 2;
            passwordField = new JPasswordField(20);
            passwordField.setPreferredSize(new Dimension(200, 27));
            contentPane.add(passwordField, gbc);


            JPanel panel = new JPanel();
            JButton save = new JButton("保存");
            save.addActionListener(new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    userDao.insert(new User(null, usernameField.getText(), passwordField.getText()));
                    refreshData(userDao.listAll());
                    dispose();
                }
            });
            panel.add(save);


            setLayout(new BorderLayout());
            add(contentPane, BorderLayout.CENTER);
            add(panel, BorderLayout.SOUTH);
        }
    }


}
